<?php

/**
 * 作者：云喵软件开发工作室
 * 官网：https://www.meoyun.com
 */

namespace app\api\controller;

use app\model\MessageModel;
use app\model\UsersModel;
use app\service\MessageService;
use app\service\WeChatMnpService;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use support\Db;
use support\Request;
use app\model\CommentsModel;

class Comments extends BaseApi
{

    //发布评论
    public function publish(Request $request)
    {
        $userId = $this->getUserId();

        $user = UsersModel::checkUser($userId);

        try {
            $params = v::input($request->post(), [
                'to_user_id' => v::notEmpty()->setName("回复用户ID"),
                'parent_id' => v::nullable(v::stringType())->setName("父级ID"),
                'post_id' => v::notEmpty()->stringType()->setName('帖子ID'),
                'content' => v::notEmpty()->setName('内容'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }


        $params["user_id"] = $userId;

        (new WeChatMnpService())->msgSecCheck($user["openid"],$params["content"]);

        $comment = CommentsModel::create($params);

        $comment = CommentsModel::with(["user","to_user"])->find($comment->id);

        if($userId !=  $params["to_user_id"]){
            // 发送点赞消息给帖子作者
            MessageService::sendMessage(
                $userId,
                $params["to_user_id"],
                $params["content"],
                MessageModel::TYPE_COMMENT,
                $params["post_id"],
            );
        }

        Db::table('post')->where("id",$params["post_id"])->increment('comment_count'); //评论量自增

        return $this->success($comment);
    }

    //获取父级评论列表
    public function getParentComments(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'post_id' => v::notEmpty()->stringType()->setName('帖子ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $paginate = CommentsModel::where('post_id', $params['post_id'])
            ->where('parent_id', '0')
            ->withCount(['replies' => function ($query) {
                $query->where('parent_id', '!=', '0');
            }])
            ->with(['user', 'to_user'])
            ->orderBy('created_at', 'desc')
            ->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($paginate);
    }

    //获取子级评论列表
    public function getChildComments(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'parent_id' => v::notEmpty()->stringType()->setName('评论父级ID')
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $paginate = CommentsModel::where('parent_id', $params['parent_id'])->with(['user', 'to_user'])->orderBy('created_at', 'desc')->paginate(self::DEFAULT_PAGE_SIZE);

        return $this->dataByPage($paginate);
    }
}
